package services.db;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author sergiu.marin
 * @since 26.01.2014
 */
public class DBUtils {

    public static Connection getConnection(String url, String dbName, String userName, String password) {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://" + url + "/" + dbName
                    + "?user=" + userName + "&password=" + password);
        } catch (SQLException e) {
            play.Logger.debug("An error has occurred: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            play.Logger.debug("An error has occurred: " + e.getMessage());
        }
        return connection;
    }

    public static String md5(String input) {
        String md5 = null;
        if (null == input) return null;
        try {
            //Create MessageDigest object for MD5
            MessageDigest digest = MessageDigest.getInstance("MD5");
            //Update input string in message digest
            digest.update(input.getBytes(), 0, input.length());
            //Converts message digest value in base 16 (hex)
            md5 = new BigInteger(1, digest.digest()).toString(16);

        } catch (NoSuchAlgorithmException e) {
            play.Logger.debug("An error has occurred: " + e.getMessage());
        }
        return md5;
    }
}
